<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户管理</span>
        <el-button type="primary" @click="handleAdd">添加用户</el-button>
      </div>
    </template>

    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="query-form">
      <el-form-item label="关键字">
        <el-input
            v-model="queryParams.key"
            placeholder="请输入姓名关键字"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="queryParams.roleId" placeholder="请选择角色" clearable style="width: 150px">
          <el-option 
            v-for="role in roleList" 
            :key="role.id" 
            :label="role.roleName" 
            :value="Number(role.id)" 
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        v-loading="loading"
        border
    >
      <el-table-column prop="username" label="账号" align="center" header-align="center" width="200" />
      <el-table-column prop="realName" label="姓名" align="center" header-align="center" width="200" />
      <el-table-column label="头像" align="center" header-align="center" min-width="150">
        <template #default="scope">
          <el-avatar v-if="scope.row.avatar" :src="scope.row.avatar" :size="100" />
          <el-avatar v-else :size="100">{{ scope.row.realName?.charAt(0).toUpperCase() }}</el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="角色" align="center" header-align="center"  />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.limit"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="editForm" label-width="100px" ref="formRef" :rules="formRules">
        <el-form-item label="账号" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="editForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="修改密码" v-if="isEdit">
          <el-input v-model="editForm.password" type="password" placeholder="留空则不修改密码" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="editForm.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option 
              v-for="role in roleList" 
              :key="role.id" 
              :label="role.roleName" 
              :value="Number(role.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              :action="''"
              :show-file-list="false"
              :http-request="handleUpload"
              :before-upload="beforeUpload"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div style="color: #999; font-size: 12px; margin-top: 5px;">支持 jpg/png 格式，大小不超过 2MB</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { _getUserPage, _getRoles, _deleteUser, _getUserById, _updateUser, _saveUser } from '@/api/user'
import { _uploadFile } from '@/api/file'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 查询条件
const queryParams = ref({
  page: 1,
  limit: 10,
  key: '',
  roleId: null
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 角色列表
const roleList = ref([])

// 编辑对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const formRef = ref(null)
const editForm = ref({
  id: null,
  username: '',
  realName: '',
  password: '',
  roleId: null,
  avatar: ''
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 2, max: 20, message: '账号长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取角色列表
const getRoleList = () => {
  _getRoles().then(res => {
    if (res.code === 200) {
      roleList.value = res.data.roleList || []
      console.log('角色列表数据:', roleList.value)
    }
  })
}

// 查询列表
const getList = () => {
  loading.value = true
  _getUserPage(queryParams.value).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  }).catch(err => {
    ElMessage.error('查询失败')
  }).finally(() => {
    loading.value = false
  })
}

// 查询按钮
const handleQuery = () => {
  queryParams.value.page = 1
  getList()
}

// 重置按钮
const resetQuery = () => {
  queryParams.value = {
    page: 1,
    limit: 10,
    key: '',
    roleId: null
  }
  getList()
}

// 添加按钮
const handleAdd = () => {
  dialogTitle.value = '添加用户'
  isEdit.value = false
  editForm.value = {
    id: null,
    username: '',
    realName: '',
    password: '',
    roleId: null,
    avatar: ''
  }
  dialogVisible.value = true
  // 清空表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 编辑按钮
const handleEdit = (row) => {
  loading.value = true
  _getUserById(row.id).then(res => {
    if (res.code === 200) {
      dialogTitle.value = '编辑用户'
      isEdit.value = true
      const data = res.data.user
      
      // 打印数据查看结构
      console.log('获取的用户数据:', data)
      console.log('当前行数据:', row)
      
      editForm.value = {
        id: data.id,
        username: data.username,
        // 优先使用列表行数据，其次使用详情数据
        realName: row.realName || data.realName || '',
        password: '', // 编辑时不显示密码
        // 优先使用 row.roleId（从列表中获取的UserVo），其次使用 data.roleId，确保转换为数字
        roleId: Number(row.roleId || data.roleId || null),
        avatar: data.avatar || ''
      }
      
      console.log('设置的 editForm:', editForm.value)
      
      dialogVisible.value = true
      // 清空表单验证
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  }).finally(() => {
    loading.value = false
  })
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确认删除用户 "${row.realName}" 吗？`,
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    _deleteUser(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    })
  })
}

// 图片上传前的校验
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传方法
const handleUpload = async (options) => {
  const { file } = options
  
  try {
    const res = await _uploadFile(file)
    if (res.code === 200) {
      editForm.value.avatar = res.data.url || res.data.data || res.data
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(res.message || '图片上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
  }
}

// 提交编辑/新增
const submitEdit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const submitData = {
        username: editForm.value.username,
        realName: editForm.value.realName,
        roleId: editForm.value.roleId,
        avatar: editForm.value.avatar
      }
      
      if (isEdit.value) {
        // 编辑模式
        submitData.id = editForm.value.id
        // 只有当密码不为空时，才提交密码字段（修改密码）
        if (editForm.value.password && editForm.value.password.trim() !== '') {
          const trimmedPassword = editForm.value.password.trim()
          if (trimmedPassword.length > 0) {
            submitData.password = trimmedPassword
          }
        }
        // 如果密码为空，不传递password字段，后端不会更新密码
        
        _updateUser(submitData).then(res => {
          if (res.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            getList()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        })
      } else {
        // 新增模式，密码必填
        submitData.password = editForm.value.password
        
        _saveUser(submitData).then(res => {
          if (res.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            getList()
          } else {
            ElMessage.error(res.message || '添加失败')
          }
        })
      }
    }
  })
}

// 分页变化
const handlePageChange = (page) => {
  queryParams.value.page = page
  getList()
}

const handleSizeChange = (size) => {
  queryParams.value.limit = size
  queryParams.value.page = 1
  getList()
}

// 初始化
onMounted(() => {
  getRoleList()
  getList()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .query-form {
    margin-bottom: 20px;
  }
}

// 图片上传样式
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>